package cn.e3mall.search.listener;

import java.util.Arrays;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import cn.e3mall.search.service.SearchService;

public class SearchMessageListener implements MessageListener{

	@Autowired
	private SearchService searchService;
	
	@Override
	public void onMessage(Message message) {
		
		//转换成textMessage
		TextMessage textMessage = (TextMessage) message;
		
		//获取消息
		try {
			String text = textMessage.getText();
			
			if(text == null) return; //若为空
			
			//判断操作类型
			String[] textArray = text.split("-");	//分割文本，拿到操作类型标识和商品ID
			
			String opt = textArray[0];
			
			String info = textArray[1];
			
			if(opt.equals("ADD")) {
				
				//转为long
				Long itemId = new Long(info);
				
				//调用 商品添加到索引库的方法
				searchService.addItemToIndexHubByItemId(itemId);
			}else if(opt.equals("DELETE")) {
				
				//将字符串形式的数组转换成数组
				String[] ids_str = StringUtils.strip(info,"[]").split(",");

				//删除索引库中的商品数据
				searchService.deleteItemToIndexHubByItemId(ids_str);
			}
			
		} catch (JMSException e) {
			e.printStackTrace();
		}
		
	}

}
